//
//  GroupPicker.swift
//  puretennis
//
//  Created by IYE Technologies on 12/22/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class GroupPicker: AbstractPickerView {

    var groupPicker:UIPickerView = UIPickerView();
    
    var groups:[NSDictionary]! = [];
    
    var group:NSDictionary?;
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder);
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame);
        self.groups.append(firstGroup());
        
        self.groupPicker.frame = CGRect(x: margin, y: 0, width: self.frame.width - margin * 2, height: self.frame.height);
        self.groupPicker.delegate = self;
        self.groupPicker.dataSource = self;
        self.contentView.addSubview(self.groupPicker);
       
        self.loadGroups();
    }
    
    func firstGroup() ->NSDictionary{
        var allGroup = NSMutableDictionary();
        allGroup.setObject("all", forKey: "groupGuid");
        allGroup.setObject("全部", forKey: "groupName");
        return allGroup;
    }
    
    func loadGroups(){
        var url = "/api/v1/mygroups";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            self.groups = response as [NSDictionary];
            self.groups.insert(self.firstGroup(), atIndex: 0);
            self.groupPicker.reloadAllComponents();
            self.groupPicker.selectRow(1, inComponent: 0, animated: false);
            self.group = self.groups[1];
        }, errorHandle: { (error) -> Void in
            
        });
    }
    
    func selectedDefault(){
        self.groupPicker.selectRow(1, inComponent: 0, animated: false);
        self.group = self.groups[1];
    }
    
    // returns the number of 'columns' to display.
    override func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
        return 1;
    }
    
    // returns the # of rows in each component..
    override func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        return groups.count;
    }
    
    func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
        var group = self.groups[row] as NSDictionary;
        var groupName = group.objectForKey("groupName") as String;
        var groupLabel = UILabel();
        groupLabel.text = groupName;
        groupLabel.sizeToFit();
        return groupLabel;
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.group = self.groups[row];
    }
}
